<template>
  <div class="project-profit">
    <!--    start top-filter-->
    <div class="top-filter">
      <el-form :inline="true">
        <el-form-item label="签约时间">
          <el-date-picker
            :teleported="false"
            v-model="filterCondition.signingTime"
            type="daterange"
            range-separator="—"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @calendar-change="handelCalendar"
            value-format="YYYY-MM-DD"
          >
          </el-date-picker>
          <div class="quick-choose">
            <el-button @click="handleDate('month')" :type="currentDateType === 'month' ? 'primary' : ''">本月</el-button>
            <el-button @click="handleDate('year')" :type="currentDateType === 'year' ? 'primary' : ''">本年</el-button>
          </div>
        </el-form-item>
        <el-form-item label="结算时间">
          <el-date-picker
            :teleported="false"
            v-model="filterCondition.settlementTime"
            type="daterange"
            range-separator="—"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @calendar-change="handelCalendar"
            value-format="YYYY-MM-DD"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同类型">
          <el-select v-model="filterCondition.contractTypeId" clearable filterable placeholder="请输入" style="width: 240px">
            <el-option
              v-for="item in contractTypeOptions"
              :key="item.contractTypeId"
              :label="item.contractTypeName"
              :value="item.contractTypeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :icon="Search" type="primary" @click="handleSearchData">查询</el-button>
          <el-button :icon="RefreshRight" plain type="primary" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--    end top-filter-->
    <!--    start contract-statistics-->
    <div class="contract-statistics" v-loading="statisticsLoading">
      <div class="statistics-left">
        <custom-title title="合同统计总览" />
        <div class="total">
          <div class="total__left">
            <div class="total-title"><img src="@/assets/images/projectProfit/total-title.png" /> 合同总数</div>
            <div class="total-num">{{ contractTotal }}<span>个</span></div>
          </div>
          <div class="total__right">
            <img src="@/assets/images/projectProfit/contract-total-img.png" />
          </div>
        </div>
        <div class="total-detail">
          <div class="total-item" v-for="(item, index) in contractStatisticsList">
            <div class="total-item__money" :class="{ 'black-value-style': index > 1 }">{{ item.num }}</div>
            <div class="gray-name-style">
              {{ item.title }}
              <el-popover placement="top-start" :width="200" trigger="hover" :content="item.popoverText">
                <template #reference>
                  <el-icon size="14" color="#C0C4CC">
                    <QuestionFilled />
                  </el-icon>
                </template>
              </el-popover>
            </div>
          </div>
        </div>
      </div>
      <div class="statistics-right">
        <custom-title title="已结算项目总览" />
        <div class="already-settled">
          <div class="profit-list">
            <div class="profit-item" v-for="item in settledProfitList">
              <div class="profit-item__money">{{ item.num }}</div>
              <div class="name-style">
                {{ item.title }}
                <el-popover placement="top-start" :width="200" trigger="hover" :content="item.popoverText">
                  <template #reference>
                    <el-icon size="14" color="#C0C4CC">
                      <QuestionFilled />
                    </el-icon>
                  </template>
                </el-popover>
              </div>
            </div>
          </div>
          <div class="profit-detail">
            <div class="profit-detail__item" v-for="(item, index) in settleDetailList">
              <div class="left">
                <img v-if="index === 0" src="@/assets/images/projectProfit/project-income.png" />
                <img v-if="index === 1" src="@/assets/images/projectProfit/project-cost.png" />
                <div class="name-style">
                  {{ item.title }}
                  <el-popover placement="top-start" :width="200" trigger="hover" :content="item.popoverText">
                    <template #reference>
                      <el-icon size="14" color="#C0C4CC">
                        <QuestionFilled />
                      </el-icon>
                    </template>
                  </el-popover>
                </div>
                <div class="black-value-style">{{ item.num }}</div>
              </div>
              <div class="right">
                <div class="describe-list">
                  <div class="describe-item" v-for="childItem in item.children">
                    <div class="gray-name-style">
                      {{ childItem.title }}
                      <el-popover placement="top-start" :width="200" trigger="hover" :content="childItem.popoverText">
                        <template #reference>
                          <el-icon size="14" color="#C0C4CC">
                            <QuestionFilled />
                          </el-icon>
                        </template>
                      </el-popover>
                    </div>
                    <div class="black-value-style">{{ childItem.num }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!--    end contract-statistics-->
    <!--     start table-content + pagination -->
    <div class="table-content">
      <!--      start table-filter-->
      <div class="table-filter">
        <el-button type="primary" :disabled="exportLoading" :loading="exportLoading" style="width: 120px" @click="exportTable">{{
          exportLoading ? "正在导出" : "导出"
        }}</el-button>
        <div class="search-content">
          <el-input
            v-model="searchVal"
            style="width: 300px"
            clearable
            @keyup.enter="getTableData"
            @blur="getTableData"
            @clear="getTableData"
            :prefix-icon="Search"
            placeholder="请输入客户名称/小区名称/手机号"
          />
        </div>
      </div>
      <!--      end table-filter-->
      <div class="table-content-style" v-loading="tableLoading">
        <el-table show-summary :summary-method="getSummaries" :data="tableData" style="width: 100%" height="600">
          <el-table-column prop="customerId" label="客户姓名" show-overflow-tooltip min-width="100">
            <template #default="{ row }">
              <div class="customer-name" @click="toCustomerInfo(row.customerId)">
                {{ row.customerName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="contractTypeName" label="合同分类" min-width="120" />
          <el-table-column prop="customerAddress" label="小区名称" min-width="160" />
          <el-table-column label="合同收入" prop="totalAmount" width="160" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="money-detail">
                <div class="red-font">￥{{ row.receivedAmount }}</div>
                <div class="gray-font">应收：￥{{ row.totalAmount }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="增减项目收入" width="160" prop="addSubAmount">
            <template #default="{ row }">
              <div class="money-detail">
                <div class="red-font">￥{{ row.receivedAddSubAmount }}</div>
                <div class="gray-font">应收：￥{{ row.addSubAmount }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="otherAmount" label="其他收入" width="160">
            <template #default="{ row }">
              <div class="red-font">¥{{ row.otherAmount }}</div>
            </template>
          </el-table-column>
          <el-table-column label="合同成本" width="160" prop="costAmount">
            <template #default="{ row }"> ￥{{ row.costAmount }} </template>
          </el-table-column>
          <el-table-column label="整改成本" width="160" prop="companyAbarbeitungAmount">
            <template #default="{ row }"> ￥{{ row.companyAbarbeitungAmount }} </template>
          </el-table-column>
          <el-table-column label="其他成本" width="160" prop="otherCostAmount">
            <template #default="{ row }"> ￥{{ row.otherCostAmount }} </template>
          </el-table-column>
          <el-table-column label="项目利润" width="160" prop="actualProfitAmount">
            <template #default="{ row }">
              <div class="profit-detail">
                <div class="profit-detail__top">¥{{ row.actualProfitAmount }}</div>
                <div class="profit-detail__bottom">利润率:{{ row.actualProfitRate }}%</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="partner" label="工程状态" width="120">
            <template #default="{ row }">
              <div
                class="status-tag"
                :style="{
                  color: engineeringStatusObj[row.projectStatus].color,
                  background: engineeringStatusObj[row.projectStatus].bgColor
                }"
              >
                {{ row.projectStatusName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="partner" label="结算状态" width="120">
            <template #default="{ row }">
              <div
                class="status-tag"
                :style="{
                  color: settlementStatusObj[row.settleStatus].color,
                  background: settlementStatusObj[row.settleStatus].bgColor
                }"
              >
                {{ row.settleStatusName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="signingTime" width="200" label="合同签订日期" />
          <el-table-column prop="settleTime" width="200" label="合同结算日期" />
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination
          v-model:current-page="pageInfo.current"
          v-model:page-size="pageInfo.size"
          :page-sizes="[50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSearchData"
          @current-change="handleSearchData"
        />
      </div>
    </div>
    <!--    end table-content + pagination-->
  </div>
</template>

<script setup>
import { dayjs } from "element-plus";
import { ref, getCurrentInstance, h } from "vue";
import { RefreshRight, Search } from "@element-plus/icons-vue";
import { contractType, statisticsAmount, contractProfitTable, exportTableData } from "@/apis/projectProfit";
import {
  originContractStatistics,
  originSettledProfit,
  originSettledDetail,
  initFilterCondition,
  engineeringStatusObj,
  settlementStatusObj
} from "./config";
import exportExcel from "@/utils/exportExcel";
import { microAppMainRouter } from "@/microApp";

const { proxy } = getCurrentInstance();

// 搜索
const searchVal = ref("");
// TODO: 禁用比较复杂，暂时不用
const disabledDate = time => {
  // if (!filterCondition.value.settlementTime.length) {
  //   return;
  // }
  // const today = new Date();
  // const twoYearsLater = new Date();
  // twoYearsLater.setFullYear(today.getFullYear() + 2);
  // return time.getTime() > twoYearsLater.getTime();
};
const handelCalendar = data => {
  // const isSelected = data.every(item => {
  //   return item;
  // });
  // if (!isSelected) return;
  // !isTwoYearsInset(data) && proxy.$modal.msgError("时间范围不能超过2年，请重新选择！");
};
const isTwoYearsInset = data => {
  const [startDate, endDate] = data;
  let start = dayjs(startDate);
  let end = dayjs(endDate);
  if (start.isAfter(end)) {
    [start, end] = [end, start];
  }
  const yearsDiff = end.diff(start, "year");
  return yearsDiff <= 2;
};

const filterCondition = ref({ ...initFilterCondition });
const contractTypeOptions = ref([]);
const getContractType = async () => {
  const { data } = await contractType();
  contractTypeOptions.value = data ?? [];
};
const currentDateType = ref("month");
const handleDate = type => {
  currentDateType.value = type;
  if (type === "month") {
    const firstDayOfMonth = dayjs().startOf("month").format("YYYY-MM-DD");
    const lastDayOfMonth = dayjs().endOf("month").format("YYYY-MM-DD");
    filterCondition.value.signingTime = [firstDayOfMonth, lastDayOfMonth];
  }
  if (type === "year") {
    const startOfYear = dayjs().startOf("year").format("YYYY-MM-DD");
    const endOfYear = dayjs().endOf("year").format("YYYY-MM-DD");
    filterCondition.value.signingTime = [startOfYear, endOfYear];
  }
};
const handleSearchData = () => {
  if (
    !isTwoYearsInset(filterCondition.value?.signingTime ?? []) ||
    !isTwoYearsInset(filterCondition.value?.settlementTime ?? [])
  ) {
    return proxy.$modal.msgError("时间范围不能超过2年，请重新选择！");
  }
  getStatisticsAmount();
  getTableData();
};
const resetSearch = () => {
  filterCondition.value = { ...initFilterCondition };
  pageInfo.value.current = 1;
  handleSearchData();
};

//统计
const statisticsLoading = ref(false);
const contractTotal = ref(0); //合同个数
const contractStatisticsList = ref([]); //统计数据
const settledProfitList = ref([]); //利润
const settleDetailList = ref([]); //已结算项目
const getStatisticsAmount = async () => {
  statisticsLoading.value = true;
  dealParams();
  const { data } = await statisticsAmount(filterCondition.value);
  dealStaticData(originContractStatistics, data.contractStatisticsVo, contractStatisticsList);
  dealStaticData(originSettledProfit, data.settleStatisticsVo, settledProfitList);
  dealStaticData(originSettledDetail, data.settleStatisticsVo, settleDetailList);
  contractTotal.value = data.contractStatisticsVo?.contractCount;
  statisticsLoading.value = false;
};
const dealStaticData = (originData, interfaceData, newData) => {
  originData.map(item => {
    const prefix = item?.prefix ?? "";
    const suffix = item?.suffix ?? "";
    item.num = prefix + interfaceData[item.fieldParam] + suffix;
    item?.children?.length &&
      item.children.map(child => {
        const prefix = child?.prefix ?? "";
        const suffix = child?.suffix ?? "";
        child.num = prefix + interfaceData[child.fieldParam] + suffix;
      });
  });
  newData.value = originData;
};
const dealParams = () => {
  const { signingTime, settlementTime } = filterCondition.value;
  if (signingTime && signingTime.length) {
    filterCondition.value.startSignDate = signingTime[0] + " 00:00:00";
    filterCondition.value.endSignDate = signingTime[1] + " 23:59:59";
  } else {
    filterCondition.value.startSignDate = "";
    filterCondition.value.endSignDate = "";
  }
  if (settlementTime && settlementTime.length) {
    filterCondition.value.startSettleTime = settlementTime[0] + " 00:00:00";
    filterCondition.value.endSettleTime = settlementTime[1] + " 23:59:59";
  } else {
    filterCondition.value.startSettleTime = "";
    filterCondition.value.endSettleTime = "";
  }
};

//表格
const pageInfo = ref({
  current: 1,
  size: 200
});
const tableLoading = ref(false);
const total = ref(0);
const tableData = ref([]);
const tableSum = ref({});
const getTableData = async () => {
  tableLoading.value = true;
  dealParams();
  const { data } = await contractProfitTable(
    {
      ...pageInfo.value
    },
    {
      ...filterCondition.value,
      ...{ key: searchVal.value }
    }
  );
  tableData.value = data.page?.list;
  tableSum.value = data?.total;
  total.value = data.page?.total;
  tableLoading.value = false;
};
const toCustomerInfo = customerId => {
  microAppMainRouter("push", {
    path: "/crm/client-info",
    query: {
      customerId
    }
  });
};

const getSummaries = params => {
  const { columns, data } = params;
  const sums = [];
  const {
    totalAmount,
    addSubAmount,
    otherAmount,
    costAmount,
    companyAbarbeitungAmount,
    otherCostAmount,
    actualProfitAmount,
    actualProfitRate,
    receivedAddSubAmount,
    receivedAmount
  } = tableSum.value;
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    switch (column.property) {
      case "totalAmount":
        sums[index] = h("div", {}, [h("p", {}, "￥" + receivedAmount), h("p", {}, "应收:￥" + totalAmount)]);
        break;
      case "addSubAmount":
        sums[index] = h("div", {}, [h("p", {}, "￥" + receivedAddSubAmount), h("p", {}, "应收:￥" + addSubAmount)]);
        break;
      case "otherAmount":
        sums[index] = `￥${otherAmount}`;
        break;
      case "costAmount":
        sums[index] = `￥${costAmount}`;
        break;
      case "companyAbarbeitungAmount":
        sums[index] = `￥${companyAbarbeitungAmount}`;
        break;
      case "otherCostAmount":
        sums[index] = `￥${otherCostAmount}`;
        break;
      case "actualProfitAmount":
        sums[index] = h("div", {}, [h("p", {}, "￥" + actualProfitAmount), h("p", {}, "利润率" + actualProfitRate + "%")]);
        break;
    }
  });
  return sums;
};

//导出
const exportLoading = ref(false);
const exportTable = async () => {
  try {
    exportLoading.value = true;
    const res = await exportTableData({
      ...filterCondition.value,
      ...{ key: searchVal.value }
    });
    exportExcel(res, "项目利润列表");
    exportLoading.value = false;
  } catch (error) {}
};

getContractType();
handleSearchData();
</script>

<style lang="scss" scoped>
@import "index.scss";
//mixin
</style>
